package com.lagou.handler;

import com.lagou.service.protocol.RpcRequest;
import com.lagou.service.protocol.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class UserServerHandler extends ChannelInboundHandlerAdapter {

     private ApplicationContext context;

    public UserServerHandler(ApplicationContext context) {
        this.context = context;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcRequest request= (RpcRequest) msg;
        RpcResponse response=doInvokeService(request);
        ctx.writeAndFlush(response);
    }

    private RpcResponse doInvokeService(RpcRequest request) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {

        String className = request.getClassName();
        String methodName = request.getMethodName();
        Class<?>[] parameterTypes = request.getParameterTypes();
        Object[] parameters = request.getParameters();

        //反射调用类的方法
        Class<?> aClass = Class.forName(className);
        Object bean = context.getBean(aClass);
        Method method = aClass.getMethod(methodName, parameterTypes);

        Object result = method.invoke(bean, parameters);

        RpcResponse response = new RpcResponse();
        response.setCode("200");
        response.setMessage("成功");
        response.setData(request);
        return response;
    }

}
